Easy2Siksha.com
GNDU Question Paper-2024
Bachelor of Computer Application
(BCA) 3
rd
Semester (CBGS)
INTRODUCATION TO PYTHON PROGRAMMING
Time Allowed: Three Hours Max. Marks: 100
Note: Attempt Five questions in all, selecting at least One question from each section. The
Fifth question may be attempted from any section. All questions carry equal marks.
SECTION-A
1.(a) What are the technical strengths of Python language? Explain.
(b) Define variables and identifiers used by Python.
2.(a) What is the use of lists in Python? Explain.
(b) Explain the usage of selection control by writing Python program.
SECTION-B
3.(a) Write a Python program to find the smallest of three numbers using if-else control
structure.
(b) Write a program to find factorial of a number illustrating recursion.
4.(a) Discuss the role of package
(b) Explain the concept of Python modules.
SECTION - C
(4) Write a Python program to read text from a text-file
Easy2Siksha.com
(b) Differentiate readline () & readlines () functions.
5.(a) Write a Python code to find area of a square is using enares of object oriented
programming
(b) What is the significance of inheritance Explain.
SECTION-D
7. How SQL database connection is carried out using Pythor? Explain.
8. Explain the following concepts by taking suitable examples:
(a) Programming with multiple tables.
(b) Data modelling.
Easy2Siksha.com
GNDU Answer Paper-2024
Bachelor of Computer Application
(BCA) 3
rd
Semester (CBGS)
INTRODUCATION TO PYTHON PROGRAMMING
Time Allowed: Three Hours Max. Marks: 100
Note: Attempt Five questions in all, selecting at least One question from each section. The
Fifth question may be attempted from any section. All questions carry equal marks.
SECTION-A
1.(a) What are the technical strengths of Python language? Explain.
(b) Define variables and identifiers used by Python.
Ans: A New Beginning: Why Python Feels Like Magic
Imagine you walk into a huge library. The library has books of every language in the world
some are complicated, full of strange symbols, while others are neat, simple, and almost
musical to read.
Among all those languages, there is one book written in such a way that even a beginner can
pick it up and understand. The sentences are short, clean, and powerful. Yet, the same book
can also be read by scientists, engineers, and AI experts to solve the world’s toughest
problems.
That “book” is none other than Python programming language.
Python is not just a tool; it’s like a teacher who makes even the most difficult concepts look
easy. That’s why students, researchers, web developers, data scientists, and even game
designers use it so widely.
Now, let’s carefully unfold the two parts of the question:
1. Technical strengths of Python language.
2. Definition of variables and identifiers used by Python.
We’ll explore them slowly, as if telling a story of discovery.
Easy2Siksha.com
Part (a): Technical Strengths of Python
When we say "technical strengths," we mean the qualities that make Python stand out
compared to other programming languages like C, C++, or Java. Imagine Python as a
superhero in the coding worldit has certain superpowers that make life easier for
programmers.
Let’s explore these strengths one by one:
1. Simplicity and Readability
Python’s first superpower is simplicity.
Most programming languages are like puzzleslots of curly brackets { }, semicolons ;, and
rules that make them tough for beginners. Python, on the other hand, feels like English.
Example:
print("Hello, World!")
That’s all you need to write your first program in Python. No complicated boilerplate like in
C:
#include <stdio.h>
int main() {
printf("Hello, World!");
return 0;
}
See the difference? Python is simple and clear, making it perfect for both beginners and
professionals.
2. Interpreted Language
Python is an interpreted language, which means you don’t have to “compile” it before
running. You write the code, and Python executes it line by line.
Think of it like this: If you’re reading a play, Python acts like a narrator who reads each line
out loud as soon as it sees it. You don’t have to wait until the whole play is written.
3. High-Level Language
Python allows you to focus on what you want to do, not on the small details of how the
computer does it.
Easy2Siksha.com
For example, in C, if you want to open a file, you must worry about pointers, buffers, and
closing the file carefully. In Python, it’s just:
with open("data.txt", "r") as file:
content = file.read()
It feels like giving instructions to a human assistant rather than to a stubborn machine.
4. Cross-Platform
Python is like a traveler who feels at home everywhere. Whether you’re on Windows, Linux,
or macOS, the same Python program works without modification.
This makes it ideal for students in labs, companies running big servers, and even mobile app
developers.
5. Large Standard Library
Python comes with a treasure chest of tools called the “standard library.”
Want to work with math? Use math.
Want to deal with dates? Use datetime.
Want to send emails? Use smtplib.
It’s like carrying a Swiss Army knife—you always have the right tool for the job.
6. Object-Oriented and Functional
Python is flexible. If you like to think in terms of objects (like cars, students, accounts), you
can use object-oriented programming.
If you prefer functions (small building blocks that process data), Python supports that too.
So, whether you’re an artist painting big pictures (OOP) or a craftsman carving small statues
(functions), Python welcomes both styles.
7. Extensible and Embeddable
Python plays well with others.
Easy2Siksha.com
You can extend Python by writing some parts in C or C++ for speed.
You can also embed Python inside another language to make that language smarter.
Think of Python as a friendly neighbor who doesn’t mind sharing tools.
8. Huge Community and Libraries
Perhaps Python’s greatest strength is not technical but social—its community. Millions of
developers contribute new libraries daily.
Want to do AI? Use TensorFlow or PyTorch.
Want data analysis? Use Pandas.
Want web development? Use Django or Flask.
No matter what problem you face, someone has already written a Python solution for it.
9. Dynamically Typed
Unlike C, where you must declare a variable’s type (int x;), Python is relaxed:
x = 10
x = "Hello"
The same variable can change its type! Python handles it in the background.
It’s like having a magical box—you can put an apple, then later replace it with a book, and
Python won’t complain.
10. Strong in Emerging Fields
Python has become the king of AI, machine learning, and data science.
Why? Because its syntax is simple, so scientists focus on solving problems instead of fighting
with the language. That’s why Google, NASA, Netflix, and Instagram all rely heavily on
Python.
Summary of Strengths
If we summarize, Python’s technical strengths are:
Easy2Siksha.com
Simple and readable.
Interpreted and high-level.
Portable across platforms.
Rich libraries and community support.
Supports multiple programming paradigms.
Dynamically typed yet powerful.
Perfect for modern fields like AI, data science, and automation.
Python is like a “universal key” that opens almost every programming door.
Part (b): Variables and Identifiers in Python
Now, let’s move to the second part of the question: variables and identifiers.
Think of a classroom. The teacher says: “You, in the red shirt, come here.” That’s confusing.
But if the teacher says: “Rohit, please come here,” everyone knows exactly who she means.
That’s what identifiers and variables do in programmingthey give names to things, so the
computer knows what you’re talking about.
1. What is a Variable?
A variable is like a container, a box where you can store data.
Example:
age = 20
name = "Aman"
age is a box containing the number 20.
name is a box containing the string "Aman".
The beauty of Python is that you don’t need to declare the type in advance—it guesses
automatically.
2. What is an Identifier?
An identifier is simply the name you give to a variable, function, class, or module.
In the above example:
age and name are identifiers.
Easy2Siksha.com
Identifiers are like labels you stick on boxes so you don’t get confused about what’s inside.
3. Rules for Identifiers in Python
Python has some rules for naming identifiers:
1. They can contain letters (AZ, az), digits (09), and underscores _.
2. They cannot start with a digit.
󷄧󼿒 student1
󽆱 1student
3. They are case-sensitive.
Age and age are different.
4. They cannot use Python’s reserved keywords like if, while, class.
5. They should be meaningful.
󷄧󼿒 marks, salary
󽆱 x1, abc
4. Examples of Variables and Identifiers
roll_no = 101 # valid
student_name = "Raj"
_total_marks = 450
PI = 3.14
Invalid ones:
1name = "Ravi" # starts with digit
if = 10 # reserved word
my-name = "Ajay" # hyphen not allowed
A Quick Comparison with C (Program Example)
To show how variables and identifiers look in C, let’s write a small program.
C Program: Variables and Identifiers
#include <stdio.h>
int main() {
int age = 20; // integer variable
float salary = 35000; // float variable
char grade = 'A'; // character variable
printf("Age: %d\n", age);
printf("Salary: %.2f\n", salary);
printf("Grade: %c\n", grade);
Easy2Siksha.com
return 0;
}
Here:
age, salary, and grade are identifiers.
The values 20, 35000, and 'A' are stored inside variables.
The same thing in Python is even simpler:
age = 20
salary = 35000.0
grade = 'A'
print("Age:", age)
print("Salary:", salary)
print("Grade:", grade)
See how Python reduces complexity? That’s why it’s called a beginner-friendly language.
Conclusion
If we look back, Python is like a superhero language. Its technical strengthssimplicity,
portability, huge libraries, and adaptabilitymake it the backbone of modern programming.
At the same time, the concepts of variables (containers for data) and identifiers (names for
those containers) make coding in Python smooth and logical.
Python teaches us an important lesson: greatness lies in simplicity. It makes computers feel
less like cold machines and more like helpful friends.
That is why Python is not only a tool of the present but also the future.
2.(a) What is the use of lists in Python? Explain.
(b) Explain the usage of selection control by writing Python program.
Ans: 󷊆󷊇 A Different Beginning
Imagine you are at home, planning your day. You wake up and start making a small "to-do"
list:
1. Brush teeth
2. Eat breakfast
3. Attend classes
4. Play games
Easy2Siksha.com
5. Revise notes
This little list saves you from the headache of remembering everything. If you suddenly
remember that you have to "buy groceries," you can simply add it to the list. If you want to
remove "play games," you just cut it out. If you want to change "eat breakfast" to "eat
healthy breakfast," you can update it.
Now think about this: if you as a human need lists to organize life, computers also need
lists to organize data. That’s where Python lists come into play.
So today, let’s travel into the world of Python with this everyday example and see:
1. What are lists in Python and why do we use them?
2. What is selection control (decision-making) and how do we write a program using
it?
We’ll not just look at the boring definition but unfold it like a real-life story, making it
simple, engaging, and crystal clear.
󷈷󷈸󷈹󷈺󷈻󷈼 Part (a): What is the Use of Lists in Python?
1. Understanding Lists through Real Life
Suppose you go to a fruit shop. The shopkeeper shows you a basket of fruits:
Apple
Mango
Banana
Grapes
This basket is just like a Python list. A list is a collection of items kept together under one
name. Instead of remembering fruits one by one, you remember the "basket."
In Python, we can write this basket as:
fruits = ["Apple", "Mango", "Banana", "Grapes"]
Here, fruits is the name of the list, and inside it, we have four items.
2. Why Do We Need Lists?
Let’s imagine life without lists in Python.
If you had to store 10 student names, you would need 10 separate variables:
Easy2Siksha.com
student1 = "Ravi"
student2 = "Anita"
student3 = "Rahul"
...
student10 = "Simran"
That looks messy, right? What if the teacher suddenly asks to add 5 more students? You’d
go crazy creating more variables.
Instead, with a list:
students = ["Ravi", "Anita", "Rahul", "Simran"]
You just keep adding names into the list. One single variable is enough to store hundreds or
thousands of items. That’s why lists are like containers or baskets they hold multiple
items neatly.
3. Features of Lists in Python
Ordered: Items are stored in a particular order (first item is index 0, second is index
1, and so on).
Mutable: You can change, add, or remove items anytime.
Heterogeneous: Lists can hold different data types together (numbers, strings,
floats, even other lists).
Example:
my_list = [101, "Ravi", 99.5, True, [1, 2, 3]]
This list has an integer, string, float, boolean, and even another list inside it.
4. Operations You Can Perform on Lists
(i) Accessing Items
Just like a cupboard has shelves, lists have positions called indexes.
fruits = ["Apple", "Mango", "Banana", "Grapes"]
print(fruits[0]) # Apple
print(fruits[2]) # Banana
(ii) Adding Items
fruits.append("Orange")
Easy2Siksha.com
print(fruits) # ['Apple', 'Mango', 'Banana', 'Grapes', 'Orange']
(iii) Removing Items
fruits.remove("Mango")
print(fruits) # ['Apple', 'Banana', 'Grapes', 'Orange']
(iv) Changing Items
fruits[1] = "Pineapple"
print(fruits) # ['Apple', 'Pineapple', 'Grapes', 'Orange']
(v) Length of a List
print(len(fruits)) # 4
5. Why Are Lists Useful in Real Life Programming?
Storing data: Names of students, prices of products, marks of exams.
Performing calculations: Summing numbers in a list, finding averages.
Organizing tasks: To-do apps use lists internally.
Handling real-world data: In machine learning or data analysis, thousands of values
are stored in lists.
So, in short, lists are the heart of Python data storage. Without them, life would be chaotic,
just like running a shop without keeping items properly in racks.
󷈷󷈸󷈹󷈺󷈻󷈼 Part (b): Explain the Usage of Selection Control
Now, let’s move to the second part: selection control.
1. What Is Selection Control?
Imagine you are standing at a crossroads. One road goes left, another right. Depending on
your decision, you choose a road.
Similarly, in programming, computers often face situations where they have to choose one
action among many possible actions. This decision-making ability is called selection control.
In Python, we use if, elif, and else statements for this.
Easy2Siksha.com
2. How Does It Work?
Think about exam results. If a student scores:
90 or above → Print "Excellent"
75 to 89 → Print "Good"
50 to 74 → Print "Average"
Below 50 → Print "Fail"
The computer needs to "select" the right action based on marks.
3. Example Program in Python
# Program to check grade of a student using selection control
marks = int(input("Enter your marks: "))
if marks >= 90:
print("Excellent! You got grade A.")
elif marks >= 75:
print("Good! You got grade B.")
elif marks >= 50:
print("Average. You got grade C.")
else:
print("Sorry, you have failed.")
4. Explanation of the Program
if: First condition is checked. If true, it runs and stops checking further.
elif: If the first is false, it checks the next condition.
else: If none are true, this block runs.
So, if a student enters marks = 82:
The computer first checks marks >= 90 → false.
Then checks marks >= 75 → true.
It prints: "Good! You got grade B."
This is how selection control helps computers make decisions just like humans.
5. More Real-Life Examples of Selection Control
ATM machine: If you enter the right PIN → access account; else → "Invalid PIN."
Easy2Siksha.com
Online shopping: If the product is in stock → show "Buy Now"; else → show "Out of
Stock."
Traffic lights: If red → stop; if yellow → slow down; if green → go.
Everywhere you see "if this happens, do this; otherwise, do something else," you’re
witnessing selection control in action.
󷈷󷈸󷈹󷈺󷈻󷈼 Blending Lists with Selection Control
Sometimes, lists and selection control work together.
Example: Checking if an item is in the shopping cart:
cart = ["Shoes", "Shirt", "Watch"]
item = input("Enter the item you want to buy: ")
if item in cart:
print(item, "is available in your cart.")
else:
print(item, "is not found in your cart.")
This makes programs dynamic and interactive, combining the power of lists (to hold
multiple values) and selection control (to make decisions).
󷈷󷈸󷈹󷈺󷈻󷈼 Wrapping It All Together
Lists are like baskets or containers that help store and manage multiple items under
one name. They are flexible, ordered, and powerful.
Selection control gives Python the ability to "think" and "decide," just like we
humans do when we face different situations.
Together, they make Python programs not just mechanical but intelligent and useful
in real-world applications.
󽆪󽆫󽆬 Final Thoughts
Programming may look like just writing lines of code, but in reality, it is about solving
problems in life. Lists help you organize your data, and selection control helps you make
decisions based on that data.
Think of a student management system:
Easy2Siksha.com
The list stores all the students’ details.
Selection control decides who passes, who fails, or who gets a scholarship.
That’s how Python, step by step, imitates human intelligence and makes our lives easier.
SECTION-B
3.(a) Write a Python program to find the smallest of three numbers using if-else control
structure.
(b) Write a program to find factorial of a number illustrating recursion.
Ans: 󷊆󷊇 A Fresh Beginning
Imagine you are sitting in a classroom, and your programming teacher writes two questions
on the board:
1. Write a Python program to find the smallest of three numbers using if-else.
2. Write a Python program to find factorial of a number using recursion.
At first glance, it might look like “just another coding exercise.” But if you take a moment
and really think about it, both these questions carry deeper lessons. They are not only about
writing a program but also about understanding how humans think, decide, and repeat
actions and how a computer mimics these human abilities through programming.
So, let us start a journey where we connect real-life situations to programming logic, making
these topics feel less like robotic commands and more like storytelling with purpose.
󷈷󷈸󷈹󷈺󷈻󷈼 Part (a): The Smallest of Three Numbers (Using if-else)
󷘹󷘴󷘵󷘶󷘷󷘸 The Real-Life Problem
Imagine you and two of your friends decide to compare your heights to see who is the
shortest. None of you has a measuring tape, but you can still “visually” compare. First, you
look at yourself and one friend, decide who is shorter, and then compare the shorter one
with the third person. At the end of this mental process, you arrive at the answer: “Yes, this
friend is the shortest among us.”
This is exactly how if-else control structure works in programming. It’s the way computers
make decisions based on conditions.
Easy2Siksha.com
󽁌󽁍󽁎 How if-else Works?
In simple words, an if-else statement is like asking questions and branching into different
answers:
If condition A is true → do this.
Else if condition B is true → do something else.
Else → do the default thing.
This mimics our natural way of deciding.
󼪔󼪕󼪖󼪗󼪘󼪙 Applying to Three Numbers
Now, to find the smallest of three numbers (say a, b, c), we need to check:
1. If a is smaller than both b and c, then a is the smallest.
2. Else, if b is smaller than both a and c, then b is the smallest.
3. Otherwise, c must be the smallest.
See how beautifully simple it is? We are just comparing step by step, just like how humans
would compare their heights.
󹳾󹳿󹴀󹴁󹴂󹴃 The Python Program
# Program to find the smallest of three numbers using if-else
# Taking input from the user
a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))
c = int(input("Enter the third number: "))
# Using if-else to find the smallest
if a <= b and a <= c:
print("The smallest number is:", a)
elif b <= a and b <= c:
print("The smallest number is:", b)
else:
print("The smallest number is:", c)
󹴞󹴟󹴠󹴡󹶮󹶯󹶰󹶱󹶲 Explanation of the Code
Input step: We ask the user to enter three numbers.
Easy2Siksha.com
Condition check:
o First, we check if a is less than or equal to both b and c. If true, a is the
smallest.
o If not, then we check if b is less than or equal to both a and c. If true, b is the
smallest.
o Otherwise, c must be the smallest.
This covers all cases whether the numbers are equal, different, or in any order.
󷔬󷔭󷔮󷔯󷔰󷔱󷔴󷔵󷔶󷔷󷔲󷔳󷔸 Real-Life Connection
Think about three contestants in a race. To find the winner (who comes first), you don’t
need to check every possibility exhaustively. You just compare step by step, eliminate larger
ones, and keep the smallest. Computers are fast, but they too rely on this very human-like
process.
󷈷󷈸󷈹󷈺󷈻󷈼 Part (b): Factorial Using Recursion
󷘹󷘴󷘵󷘶󷘷󷘸 The Real-Life Problem
Have you ever seen how dominoes fall? The first domino pushes the second, the second
pushes the third, and so on. This chain reaction is what recursion feels like in programming.
Now, let’s connect this to factorial.
The factorial of a number n (written as n!) is:
n! = n × (n-1) × (n-2) × ... × 2 × 1
For example:
5! = 5 × 4 × 3 × 2 × 1 = 120
3! = 3 × 2 × 1 = 6
Notice something? Every factorial depends on the factorial of a smaller number.
5! = 5 × 4!
4! = 4 × 3!
…and so on.
This naturally lends itself to recursion, where a function calls itself with a smaller value until
it reaches a base condition.
Easy2Siksha.com
󽁌󽁍󽁎 What is Recursion?
Recursion is like giving a task back to yourself but with a smaller workload.
Example in life:
Imagine you need to arrange 10 books.
You put 1 book on the shelf and then say: “Okay, future me, arrange the remaining 9
books.”
The future you repeats the same process until only 1 book is left.
That’s recursion!
󹳾󹳿󹴀󹴁󹴂󹴃 The Python Program
# Program to find factorial of a number using recursion
def factorial(n):
# Base case: factorial of 0 or 1 is 1
if n == 0 or n == 1:
return 1
else:
# Recursive case: n * factorial of (n-1)
return n * factorial(n - 1)
# Taking input from the user
num = int(input("Enter a number: "))
# Calculating factorial
result = factorial(num)
# Displaying the result
print("The factorial of", num, "is:", result)
󹴞󹴟󹴠󹴡󹶮󹶯󹶰󹶱󹶲 Explanation of the Code
Base case: If n is 0 or 1, return 1 (because by definition, 0! = 1 and 1! = 1).
Recursive case: Otherwise, return n * factorial(n-1).
This recursive call reduces the problem size each time, just like breaking down a big
task into smaller ones.
󷔬󷔭󷔮󷔯󷔰󷔱󷔴󷔵󷔶󷔷󷔲󷔳󷔸 Real-Life Connection
Easy2Siksha.com
Think about climbing down stairs. You’re at stair n, and you decide:
“I’ll take one step down, and future me will handle the remaining n-1 steps.”
Eventually, you’ll reach the ground floor (base case), and the journey is complete.
󷇮󷇭 Why These Concepts Matter?
If-else teaches us decision-making. Life is full of choices: what to eat, where to go,
how to act. Computers mimic this choice-making with if-else.
Recursion teaches us breaking down complex tasks into simpler ones. Many real-
life processes, from Russian nesting dolls to peeling onions layer by layer, are
recursive in nature.
When you master these small concepts, you’re not just learning programming you’re
learning how to think systematically and logically, just like a computer.
󹾱󹾴󹾲󹾳 Historical & Broader Perspective
The idea of conditional logic (if-else) is as old as human reasoning. In fact, early
philosophers like Aristotle framed logical rules very similar to programming
conditions.
Recursion, on the other hand, has fascinated mathematicians for centuries. Think of
the Fibonacci series or fractals in nature both are recursive patterns.
Programming simply gives us a practical way to express them.
󷒮󷒯󷒰󷒱 Wrapping Up in Story Style
So, let’s recap our journey:
We started by comparing three friends’ heights to understand if-else.
Then we watched dominoes fall and imagined staircases to grasp recursion.
We wrote simple Python programs to solve both problems.
We realized that programming isn’t just about machines it’s about how humans
think, decide, and repeat tasks.
These questions, though small, are like the seeds of a giant tree. If you nurture them, they’ll
grow into deeper understanding of algorithms, problem-solving, and logical thinking.
Easy2Siksha.com
4.(a) Discuss the role of package
(b) Explain the concept of Python modules.
Ans: When we first begin learning programming, we often imagine it like writing a single
notebook of code. One page, one notebook, and everything written there. At first, this feels
fine. But soon, as programs grow bigger, the notebook gets messytoo many pages, too
many scribbles, and it becomes almost impossible to find the exact piece of code you wrote
two weeks ago.
Now imagine if you had a library instead of a single notebook. In this library, every subject
has its own separate book, and inside each book, chapters are neatly organized. If you want
to learn about “math formulas,” you simply pick up the Math Book. If you want “science
experiments,” you take the Science Book. This way, you don’t have to carry the whole library
everywhereyou carry just the book you need.
This idea in Python is made possible through modules and packages.
Modules are like individual books containing useful information (code).
Packages are like a whole collection of books arranged together in a shelf, neatly
organized.
Let us slowly and clearly walk through both parts of the question:
(a) The Role of Package in Python
1. What is a Package?
A package in Python is like a folder (or directory) that contains multiple related modules.
Imagine it as a “shelf of books” instead of a single book. Each book (module) inside deals
with a specific topic, but together they form a complete collection.
The beauty of packages is that they make large programs organized, reusable, and easier to
maintain.
Technically, a package is just a directory containing a special file called __init__.py (even if it
is empty). This file tells Python:
“Hey! This folder is not just a random folder. Treat me as a package so that people can
import modules from me.”
2. Why Do We Need Packages?
Imagine you are building a software for a school. The software must handle:
Easy2Siksha.com
Student records
Teacher records
Examination system
Fee management
If you write everything in one single file, it will become chaotic. Instead, you can create a
package named school, and inside it you can have:
students.py
teachers.py
exams.py
fees.py
Now the program is clean and modular. Whenever you need to work on exams, just open
exams.py. No need to get lost in thousands of lines of unrelated code.
3. Structure of a Package
Here’s what a simple package looks like:
school/ ← package folder
── __init__.py tells Python this is a package
── students.py module for student management
── teachers.py module for teacher management
── exams.py module for exam system
└── fees.py ← module for fee records
4. Example Program of a Package
Let’s say we have created the above package. Now, if you want to use it in your program:
# main.py
from school import students, teachers, exams, fees
students.add_student("Rohit", 101)
teachers.add_teacher("Mrs. Sharma", "Mathematics")
exams.schedule_exam("Math Test", "15th Sept")
fees.collect_fee("Rohit", 2000)
And inside students.py, you could have something like:
def add_student(name, roll):
print(f"Student {name} with Roll No {roll} added successfully!")
Easy2Siksha.com
Similarly, teachers.py could have:
def add_teacher(name, subject):
print(f"Teacher {name} for {subject} added successfully!")
This way, the package helps us break down complexity into small, manageable parts.
5. Benefits of Packages
Organization: Keeps related modules together.
Reusability: We can reuse the same package in different projects.
Avoids Name Conflicts: If two different projects have functions named add(),
packages prevent them from clashing by giving them namespaces.
Maintainability: Easy to fix bugs or update only one module without touching the
rest.
So, the role of package is simply to act as a “library shelf” where related modules are placed
together to maintain order in our coding world.
(b) The Concept of Python Modules
1. What is a Module?
A module in Python is just a single file containing Python definitions (functions, classes,
variables) and statements.
If packages are “shelves,” then modules are “books.” And just like you borrow only one
book at a time, you can import and use only the module you need in your program.
Example: Python already gives us many ready-made modules like:
math (for mathematical operations)
random (for generating random numbers)
datetime (for handling dates and times)
You don’t need to write the code for square root again and againjust import the math
module and use math.sqrt(16) to instantly get the answer.
2. Creating Our Own Module
Creating a module is as simple as saving a Python file with functions in it.
Easy2Siksha.com
Suppose we create a file called calculator.py:
# calculator.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b != 0:
return a / b
else:
return "Division by zero is not allowed"
Now, in another file main.py, we can use this module:
# main.py
import calculator
print(calculator.add(10, 5))
print(calculator.subtract(10, 5))
print(calculator.multiply(10, 5))
print(calculator.divide(10, 0))
Output:
15
5
50
Division by zero is not allowed
This is how modules make our code reusable and neat.
3. Different Ways of Importing Modules
Python allows different ways to import modules:
1. Import the whole module
2. import math
3. print(math.sqrt(25))
4. Import specific functions
Easy2Siksha.com
5. from math import sqrt, factorial
6. print(sqrt(36))
7. print(factorial(5))
8. Import with an alias (nickname)
9. import math as m
10. print(m.pi)
4. Standard Library Modules
Python comes with a treasure chest of built-in modules. Some famous ones are:
math → mathematical functions
os → interacting with operating system
sys → system-specific parameters and functions
random → generate random numbers
datetime → work with dates and times
Example:
import random
print("Random number between 1 and 100:", random.randint(1, 100))
5. Benefits of Modules
Reusability: Write once, use multiple times.
Simplicity: Focus only on a specific task per file.
Sharing: Share modules with friends and use their modules in your projects.
Clarity: Keeps code clean and understandable.
Modules vs Packages A Simple Comparison
Feature
Module
Package
Meaning
A single file of Python code
A collection of modules (a folder with
__init__.py)
Example
math.py, calculator.py
school package containing students.py,
teachers.py etc.
Use
Used for small programs or
utilities
Used for organizing large projects
Analogy
A book
A bookshelf with multiple books
Story-like Conclusion
Easy2Siksha.com
Think of coding as building a city.
Modules are like individual houseseach house has its own design and purpose.
Packages are like entire neighbourhoodsorganizing many houses together in an
orderly fashion.
If you only need a small house, go for a module. But if you want a well-planned city, with
roads, parks, and utilities, you’ll need packages.
This combination of modules and packages is what makes Python so powerful, flexible, and
easy to work with. Without them, programming would be like dumping all building materials
in one heap and calling it a city. With them, we can build organized, beautiful, and
maintainable software systems.
SECTION - C
(4) Write a Python program to read text from a text-file
(b) Differentiate readline () & readlines () functions.
Ans: 󷈷󷈸󷈹󷈺󷈻󷈼 A Different Beginning
Imagine this: You are sitting in a library, surrounded by thick books. Now, you are asked to
read a particular book. You have two ways:
1. Read one line at a time slowly, carefully, like sipping tea.
2. Grab all the lines at once like taking all the pages together and then going through
them whenever you want.
Python’s file handling system works exactly like that! It gives us tools to open a file, read
from it, and then close it. Among these tools, readline() and readlines() are like your two
different reading strategies. But before we get into their comparison, let’s learn how Python
actually reads from a text file.
󹶆󹶚󹶈󹶉 Part 1: Reading from a Text File in Python
In the world of computers, a text file is like a diary or notebook where information is stored
in plain words. Python, being our friendly assistant, provides built-in functions to open that
diary, peek into it, and even copy or edit its contents.
Let’s first create a simple Python program to read text from a text file.
󽆐󽆑󽆒󽆓󽆔󽆕 Python Program
Easy2Siksha.com
# Program to read text from a file
# Step 1: Open the file in read mode
file = open("example.txt", "r")
# Step 2: Read the content of the file
content = file.read()
# Step 3: Display the content
print("The content of the file is:\n")
print(content)
# Step 4: Close the file
file.close()
󹴞󹴟󹴠󹴡󹶮󹶯󹶰󹶱󹶲 Explanation of the Program
Let’s break it down like a story of how Python talks to the file:
1. open("example.txt", "r")
o This is like you knocking on the door of the book (file).
o "r" means read mode you are only allowed to read, not write or erase.
2. file.read()
o Imagine opening the book and reading everything from start to finish in one
go.
o It gives you the entire content of the file as a single string.
3. print(content)
o You simply show what you have read to others.
4. file.close()
o Once you finish reading, you politely close the book to keep it safe.
So, the flow is simple: Open → Read → Print → Close.
󷊋󷊊 Part 2: Understanding readline() and readlines()
Now, here comes the heart of the question the difference between readline() and
readlines().
To explain this, let’s again go back to the library story.
󹶓󹶔󹶕󹶖󹶗󹶘 readline() The Patient Reader
Imagine you are holding a book.
You read only one line from it and stop.
If you want more, you ask again, and it will give you the next line.
This continues until you reach the end of the file.
Easy2Siksha.com
That’s exactly what readline() does.
󷷑󷷒󷷓󷷔 Example:
file = open("example.txt", "r")
line1 = file.readline()
print("First line:", line1)
line2 = file.readline()
print("Second line:", line2)
file.close()
Here, the file is read line by line. Each time you call readline(), it fetches the next line.
󹶜󹶟󹶝󹶞󹶠󹶡󹶢󹶣󹶤󹶥󹶦󹶧 readlines() The Collector
Now imagine another way: instead of reading one line at a time, you decide to copy
all the lines into a list.
Each line becomes one element of the list.
Once you have that list, you can do whatever you want loop through it, print
specific lines, etc.
󷷑󷷒󷷓󷷔 Example:
file = open("example.txt", "r")
lines = file.readlines()
print("List of lines:", lines)
file.close()
If the file has three lines, the output will look like:
['This is line one.\n', 'This is line two.\n', 'This is line three.\n']
Notice that each line, along with the newline character (\n), is stored as an element of the
list.
󹺔󹺒󹺓 Key Differences Between readline() and readlines()
Let’s make this super clear with a table and some easy-to-follow points.
Feature
readline()
readlines()
Reading style
Reads one line at a time
Reads all lines and stores them in a
list
Easy2Siksha.com
Output
A single string (line)
A list of strings (lines)
Use case
Best when you want to process file
line by line
Best when you want all lines at
once
Memory
usage
Very efficient, since it reads little
at a time
Uses more memory, since it loads
the entire file
Iteration
Can be used in loops (while/for)
Can also be looped after storing in a
list
Example
analogy
Like sipping tea, one sip at a time
Like pouring the whole cup into
your mouth
󷈷󷈸󷈹󷈺󷈻󷈼 Part 3: Bringing It All Together
Now that we know both, let’s write one more combined program to see the difference in
action.
󽆐󽆑󽆒󽆓󽆔󽆕 Python Program Demonstrating Both
# Program to show difference between readline() and readlines()
file = open("example.txt", "r")
print("Using readline():")
print(file.readline()) # Reads first line
print(file.readline()) # Reads second line
file.close()
print("\nUsing readlines():")
file = open("example.txt", "r")
all_lines = file.readlines()
print(all_lines) # Reads all lines into a list
file.close()
󼭯󼭭󼭮 Storytelling Recap
So, let’s imagine again:
You are in a library with a diary.
If you want to enjoy slowly, you go line by line (readline()).
If you want to take everything in one go and keep it for later, you use readlines().
Python simply helps you choose whichever way suits your problem.
󷇮󷇭 Real-Life Uses
readline() is helpful when files are extremely large (like log files or server data). It
prevents memory overload by reading little by little.
Easy2Siksha.com
readlines() is useful when files are small to medium-sized and you want to analyze or
manipulate all lines together (like reading student names, scores, or a poem).
󽆪󽆫󽆬 Why This Question Is Beautiful
This question may look technical, but at its heart, it is about choice. Python offers you
different ways to interact with a file whether you want to be a slow, patient reader or a
fast, grab-it-all kind of reader. Understanding this gives you flexibility in problem-solving and
shows the human-like design of Python: it respects different reading styles, just like we
humans have.
󷚚󷚜󷚛 Final Thoughts
So, to summarize:
1. Python Program to read text files uses open(), read(), and close().
2. readline() = read one line at a time (memory-friendly, step-by-step).
3. readlines() = read all lines at once into a list (fast but memory-heavy).
4. Both are important depending on the situation.
And that’s how this question, when explained as a story, feels less like coding and more like
understanding how humans naturally read a book.
6.(a) Write a Python code to find area of a square is using features of object oriented
programming
(b) What is the significance of inheritance Explain.
Ans: 󷊆󷊇 A Gentle Beginning: The Square in Real Life
Imagine you are playing in a garden and you see a small square flowerbed. Now, one
thought suddenly strikes your mind:
“How much space does this square flowerbed cover?”
That’s nothing but finding the area of a square.
In mathematics, you already know the formula:
Easy2Siksha.com
Or simply
Now, how do we take this simple idea and make it work in Python using OOP (Object-
Oriented Programming)?
That’s where the real fun begins.
󺃱󺃲󺃳󺃴󺃵 Part (a): Writing Python Code with OOP
Before jumping into the program, let us understand why OOP is important here.
In OOP, instead of just writing raw calculations, we build objects and classes.
Think of a class like a “blueprint” of a house.
And an object is the actual house built from that blueprint.
So if we want to find the area of a square:
The class will define what a square is (it has a side, and it has a method to calculate
area).
The object will represent a real square (e.g., a square with side 5 units).
󷄧󼿒 Python Code
# Defining a class for Square
class Square:
def __init__(self, side):
# Constructor to initialize the side of the square
self.side = side
def area(self):
# Method to calculate area of the square
return self.side * self.side
# Creating an object of Square class
square1 = Square(5) # Let's take side = 5
# Calculating and displaying area
print("The area of the square is:", square1.area())
󹺖󹺗󹺕 Step-by-Step Story of the Code
Easy2Siksha.com
1. class Square:
We create a class named Square. Think of it like a master plan that explains what a
square is.
2. def init(self, side):
This is the constructor. When we build a square, it automatically asks: “What is the
length of the side?”
For example, if we say Square(5), it means a square with side = 5 units.
3. def area(self):
This method is like a tool inside the class. It knows how to calculate the area using
the formula: side × side.
4. square1 = Square(5):
Here, we actually build a square object named square1. Its side is 5.
5. square1.area():
Finally, the object tells us its area, which is 5×5=255 \times 5 = 255×5=25.
Output will be:
The area of the square is: 25
󷈷󷈸󷈹󷈺󷈻󷈼 Why Use OOP Here?
You might wonder: “Couldn’t I just write side * side directly without all this class and object
business?”
Yes, you could. But OOP is like organizing your life:
Without OOP: Your clothes are scattered everywhere.
With OOP: You have cupboards, drawers, and everything is in place.
OOP gives structure, clarity, and reusability. When problems get bigger and bigger, OOP
becomes a lifesaver.
󼪍󼪎󼪏󼪐󼪑󼪒󼪓 Part (b): The Significance of Inheritance
Now let’s move to the second part of the question.
󹶓󹶔󹶕󹶖󹶗󹶘 A Simple Story to Understand Inheritance
Imagine a family. A child inherits qualities from their parents. For example:
If parents have black hair, the child might also have black hair.
If parents are musicians, the child might naturally pick up music.
In programming, inheritance works the same way.
Easy2Siksha.com
󷷑󷷒󷷓󷷔 It allows one class (child class) to inherit properties and methods from another class
(parent class).
󽁌󽁍󽁎 Technical Explanation
Parent class (or Base class): The class that gives its features to others.
Child class (or Derived class): The class that receives features from the parent class.
By using inheritance, we don’t need to write the same code again and again.
󷯚󷯛󷯜󷯝󷯞󷯟󷯠󷯡󷯢󷯣 Python Example of Inheritance
Let’s extend our square story. A square is just a special type of rectangle (because all sides
are equal).
So:
Parent class → Rectangle
Child class → Square
# Parent class
class Rectangle:
def __init__(self, length, breadth):
self.length = length
self.breadth = breadth
def area(self):
return self.length * self.breadth
# Child class (Square inherits Rectangle)
class Square(Rectangle):
def __init__(self, side):
super().__init__(side, side) # Both length and breadth are equal
for square
# Creating object of Square
square2 = Square(6)
print("The area of the square (using inheritance) is:", square2.area())
Output will be:
The area of the square (using inheritance) is: 36
󹺢 Why is Inheritance Important?
Let’s reflect on why inheritance is such a big deal.
Easy2Siksha.com
1. Reusability of Code:
You don’t have to write the same functions again and again. Once a parent class has
a feature, all children can use it.
2. Saves Time and Effort:
If you already have a Rectangle class, you don’t need to write a completely new
Square class from scratch.
3. Makes Programs Organized:
Large programs are easier to manage because you can create a hierarchy of classes.
4. Real-Life Modelling:
Just like in real life, where a “student” inherits properties from being a “human,” in
programming too, inheritance mimics nature.
󺃎󺃏󺃐󺃑󺃒 Beautiful Analogy: Library and Books
Imagine a big library. There’s a section called “Books.”
Now under “Books,” you have many categories: “Fiction,” “Non-Fiction,” “Science,”
“History,” etc.
The Book class (parent) defines common features: title, author, price.
The Fiction/Science/History classes (child) inherit these features but can also add
their own.
This way, you don’t rewrite the details of title and author in every category. They are
inherited.
󼩏󼩐󼩑 Linking Both Parts Together
Now let’s link part (a) and part (b) together:
In part (a), we created a Square class to calculate the area.
In part (b), we learned that instead of writing a separate formula for square, we can
make use of inheritance and simply borrow the logic from a Rectangle class.
This shows how OOP makes coding powerful, reusable, and closer to real life.
󷇮󷇭 The Bigger Picture of OOP
When we talk about Object-Oriented Programming, four main pillars always come into play:
1. Encapsulation binding data and methods together.
2. Abstraction hiding unnecessary details.
Easy2Siksha.com
3. Inheritance reusing features of parent class.
4. Polymorphism ability of the same function to behave differently.
In this question, we mainly focused on inheritance, but the entire OOP system is like the
foundation of modern programming.
󷘹󷘴󷘵󷘶󷘷󷘸 Final Thoughts
So, the question asked us two things:
1. To calculate the area of a square using OOP in Python.
2. To explain the significance of inheritance.
Through our little garden story, family inheritance analogy, and code examples, we’ve seen:
How OOP makes even a simple problem like “area of square” more structured.
How inheritance saves us from repeating code and models the real world beautifully.
In essence, inheritance is not just a technical tool. It’s a reflection of life itself, where
qualities and features flow from one generation to another. Programming, in this way,
becomes not just about machines, but about capturing reality in code.
SECTION-D
7. How SQL database connection is carried out using Python? Explain.
Ans: How SQL Database Connection is Carried Out Using Python?
Imagine this situation:
You are a chef in a big restaurant. Every day, hundreds of people come to eat, and you have
a kitchen full of ingredients stored neatly in different containers. Now, when a customer
orders a dish, you don’t run around randomly; instead, you know exactly where the rice is
kept, where the spices are stored, and where the vegetables are. You pick them out, cook
the dish, and serve it fresh.
Databases work exactly like this kitchen. A database stores all the “ingredients” (data), and
a programming language like Python acts like the chef. When Python needs information
(for example, the details of students, employees, or sales), it goes into the database, collects
the right data, and brings it back to you in an organized way.
But here’s the catch: just like a chef needs a key to open the kitchen and proper tools to
handle the containers, Python also needs a proper connection to access a SQL database.
Easy2Siksha.com
That connection is like a bridge between Python and the SQL database. Without this bridge,
Python cannot talk to the database, and the database cannot respond.
So, let’s take this journey step by step, like a story, to understand how Python establishes a
connection with SQL databases.
Step 1: Understanding SQL and Python’s Role
First, let’s get the characters of our story clear:
SQL (Structured Query Language): Think of SQL as the “language of the kitchen
manager.” Databases understand SQL commands like SELECT, INSERT, UPDATE, and
DELETE. For example, if you say, “SELECT all students who scored above 80,” the
database listens and gives you the results.
Python: This is the chef who speaks in Python code. But here’s the problemPython
does not directly understand SQL. Python needs a translator or a special tool called a
database connector (or driver).
So, before Python can talk to SQL, we need to install and use the right connector.
Step 2: Choosing the Database and Connector
There are different types of SQL databasesMySQL, SQLite, PostgreSQL, SQL Server,
Oracle, etc. Each one has its own rules, just like different kitchens have their own layouts.
For SQLite (lightweight and simple), Python already comes with a built-in library
called sqlite3. No installation needed!
For MySQL, we usually install mysql-connector-python or PyMySQL.
For PostgreSQL, we use psycopg2.
This means Python needs the right “key” for the right “kitchen.”
Step 3: Building the Connection (The Bridge)
To connect, Python uses the following basic steps:
1. Import the Connector Library Like picking the right key.
2. Establish Connection Using a username, password, host (like server address), and
database name.
3. Create a Cursor Object The cursor is like a waiter who carries your request to the
kitchen and brings back the dish (data).
Easy2Siksha.com
4. Execute SQL Queries You write SQL commands, and the cursor runs them in the
database.
5. Fetch the Results Get the data back into Python.
6. Close the Connection Lock the kitchen when done.
Step 4: Explaining Through a Real-Life Story
Let’s imagine you are building a small student management system. You want to store
names, roll numbers, and marks of students. Without a database, you might keep
everything in a notebook (or a text file), but searching or updating would be slow and
messy. Instead, you use a SQL database.
Now Python will help you connect to that database, add students, and fetch results.
Python Program Example with MySQL
Here is a complete example:
import mysql.connector
# Step 1: Connect to the Database
connection = mysql.connector.connect(
host="localhost", # Database server address
user="root", # Your MySQL username
password="password123", # Your MySQL password
database="school" # Database name
)
# Step 2: Create a Cursor
cursor = connection.cursor()
# Step 3: Create a Table (if not exists)
cursor.execute("""
CREATE TABLE IF NOT EXISTS students (
roll_no INT PRIMARY KEY,
name VARCHAR(100),
marks INT
)
""")
# Step 4: Insert Data
cursor.execute("INSERT INTO students (roll_no, name, marks) VALUES (1,
'Rohan', 85)")
cursor.execute("INSERT INTO students (roll_no, name, marks) VALUES (2,
'Anita', 92)")
cursor.execute("INSERT INTO students (roll_no, name, marks) VALUES (3,
'Vikram', 76)")
# Save the changes
connection.commit()
Easy2Siksha.com
# Step 5: Fetch Data
cursor.execute("SELECT * FROM students")
rows = cursor.fetchall()
print("Student Records:")
for row in rows:
print(row)
# Step 6: Close the Connection
cursor.close()
connection.close()
Explaining the Program in Story Form
Importing the Library: We told Python, “Hey, here’s the translator who understands
MySQL.”
Connecting: We unlocked the kitchen (database) with the right username, password,
and database name.
Cursor: Like a waiter, the cursor takes our request (SQL command) into the kitchen.
Creating Table: We arranged shelves (table named students) in the kitchen where
we’ll keep ingredients (data).
Inserting Data: We placed some jars (rows) filled with student information.
Fetching Data: We told the waiter to bring back all student jars, and Python
displayed them.
Closing Connection: Finally, we locked the kitchen after work was done.
Step 5: What If We Use SQLite Instead?
For small projects, SQLite is like having a mini-kitchen inside your houseno big setup
needed. Python already has sqlite3 built-in. Here’s how it works:
import sqlite3
# Step 1: Connect to SQLite database (creates file if not exists)
connection = sqlite3.connect("school.db")
# Step 2: Create cursor
cursor = connection.cursor()
# Step 3: Create table
cursor.execute("""
CREATE TABLE IF NOT EXISTS students (
roll_no INTEGER PRIMARY KEY,
name TEXT,
marks INTEGER
)
""")
# Step 4: Insert data
cursor.execute("INSERT INTO students VALUES (1, 'Rohan', 85)")
cursor.execute("INSERT INTO students VALUES (2, 'Anita', 92)")
cursor.execute("INSERT INTO students VALUES (3, 'Vikram', 76)")
Easy2Siksha.com
# Commit changes
connection.commit()
# Step 5: Fetch data
cursor.execute("SELECT * FROM students")
print(cursor.fetchall())
# Step 6: Close connection
connection.close()
Notice how similar it looks to MySQLbecause the steps are the same! The only difference
is the connector.
Step 6: Important Points Students Must Remember
1. Connection Parameters Matter
o host = Where is your database located? (localhost means same computer).
o user = Your username for login.
o password = Key to unlock.
o database = Which specific kitchen (database) are you entering?
2. Commit is Important
o Whenever you insert, update, or delete, always call commit(). It’s like
pressing “Save.”
3. Cursor Types
o Normal cursor: fetches data row by row.
o Dictionary cursor: gives results in dictionary form, easier to read sometimes.
4. Closing is Good Practice
o Always close cursor and connection. Otherwise, it’s like leaving the kitchen
open all night.
5. Error Handling
o Use try-except blocks to catch errors like wrong password, missing database,
or syntax mistakes in SQL.
Step 7: Real-World Applications
Connecting Python with SQL is not just a college exerciseit powers the real world:
Banking systems: Storing customer transactions.
E-commerce: Products, prices, and orders.
Schools and Universities: Managing student records, marks, and attendance.
Healthcare: Storing patient records and reports.
Social Media: User profiles, posts, and likes.
Everywhere you see structured data, a database is working in the background, and Python is
often used to interact with it.
Easy2Siksha.com
Step 8: Summarizing in Human Words
Think of SQL as the kitchen where food (data) is stored, and Python as the chef who
prepares dishes (applications). The database connector is the key that opens the door, and
the cursor is the waiter who carries messages back and forth.
Without the connection, Python cannot get the ingredients. With the connection, Python
becomes powerfulit can cook up any recipe you want: reports, dashboards, websites, or
even Artificial Intelligence systems that learn from the stored data.
Final Words
To answer the original question in the simplest way:
SQL database connection using Python is carried out by importing the right connector
library, establishing a connection with proper credentials, creating a cursor object,
executing SQL queries, fetching results, committing changes (if needed), and finally closing
the connection.
It’s like a smooth dance between Python and SQL, where each stepconnecting, executing,
fetching, and closingmatters. Once you master this dance, you can build real-life systems
that manage millions of records effortlessly.
8. Explain the following concepts by taking suitable examples:
(a) Programming with multiple tables.
(b) Data modelling.
Ans: Imagine you’ve just opened your own café in the heart of the city. It’s a cozy little place
with warm lights, a delicious smell of coffee, and the chatter of happy customers. But soon,
as your café grows, you realize you need to keep track of many things:
The menu items you sell (like coffee, tea, sandwiches).
The customers who visit your café.
The orders placed by those customers.
The payments they make.
At first, you try to manage everything in a single notebook but very quickly it becomes
messy. If you want to know which customer ordered which coffee, or how much a particular
customer has spent over the month, you have to flip through endless pages.
This is exactly what happens in the world of databases and programming. And this is where
our two big concepts Programming with Multiple Tables and Data Modelling step in
Easy2Siksha.com
like superheroes to organize the mess. Let’s explore them one by one through this café
story.
(a) Programming with Multiple Tables
The One Notebook Problem
In the beginning, you might think, “Why not just put everything in one big table?” For
example:
Order_ID
Item
Price
Date
1
Coffee
100
10 Sept
2
Tea
50
10 Sept
3
Sandwich
150
11 Sept
Looks fine at first, right? But now imagine Rajesh changes his phone number. You’d have to
update it in every row where Rajesh appears. Or what if you want to add a new menu item?
You’ll be stuck repeating information again and again.
This problem is called data redundancy repeating the same data multiple times. It wastes
space and can cause mistakes.
The Magic of Multiple Tables
The solution is to divide your notebook into different smaller notebooks (tables), each with
a special purpose.
1. Customer Table Stores details about customers.
2. Menu Table Stores details of food and drinks.
3. Order Table Stores information about which customer ordered which item.
4. Payment Table Stores details about payments.
Now each table is neat and clean.
Customer Table
Customer_ID
Name
Phone
1
Rajesh
98765…
2
Meena
87654…
Menu Table
Item_ID
Item_Name
Price
Easy2Siksha.com
101
Coffee
100
102
Tea
50
103
Sandwich
150
Order Table
Order_ID
Customer_ID
Item_ID
Date
1
1
101
10 Sept
2
2
102
10 Sept
3
1
103
11 Sept
Here, instead of repeating Rajesh’s name or the sandwich price again and again, we just use
IDs (Customer_ID and Item_ID). Whenever we need details, we join the tables together like
connecting puzzle pieces.
Example in Python (Using SQLite)
Let’s write a small Python program that shows how to program with multiple tables.
import sqlite3
# Step 1: Connect to database (it will create one if it doesn't exist)
conn = sqlite3.connect("cafe.db")
cursor = conn.cursor()
# Step 2: Create multiple tables
cursor.execute("""CREATE TABLE IF NOT EXISTS Customer(
Customer_ID INTEGER PRIMARY KEY,
Name TEXT,
Phone TEXT
)""")
cursor.execute("""CREATE TABLE IF NOT EXISTS Menu(
Item_ID INTEGER PRIMARY KEY,
Item_Name TEXT,
Price INTEGER
)""")
cursor.execute("""CREATE TABLE IF NOT EXISTS Orders(
Order_ID INTEGER PRIMARY KEY,
Customer_ID INTEGER,
Item_ID INTEGER,
Date TEXT,
FOREIGN KEY(Customer_ID) REFERENCES Customer(Customer_ID),
FOREIGN KEY(Item_ID) REFERENCES Menu(Item_ID)
)""")
# Step 3: Insert sample data
cursor.execute("INSERT INTO Customer VALUES (1, 'Rajesh', '9876543210')")
cursor.execute("INSERT INTO Customer VALUES (2, 'Meena', '8765432109')")
cursor.execute("INSERT INTO Menu VALUES (101, 'Coffee', 100)")
cursor.execute("INSERT INTO Menu VALUES (102, 'Tea', 50)")
Easy2Siksha.com
cursor.execute("INSERT INTO Menu VALUES (103, 'Sandwich', 150)")
cursor.execute("INSERT INTO Orders VALUES (1, 1, 101, '2025-09-10')")
cursor.execute("INSERT INTO Orders VALUES (2, 2, 102, '2025-09-10')")
cursor.execute("INSERT INTO Orders VALUES (3, 1, 103, '2025-09-11')")
conn.commit()
# Step 4: Query with JOIN to combine data from multiple tables
cursor.execute("""
SELECT Orders.Order_ID, Customer.Name, Menu.Item_Name, Menu.Price,
Orders.Date
FROM Orders
JOIN Customer ON Orders.Customer_ID = Customer.Customer_ID
JOIN Menu ON Orders.Item_ID = Menu.Item_ID
""")
for row in cursor.fetchall():
print(row)
conn.close()
Output:
(1, 'Rajesh', 'Coffee', 100, '2025-09-10')
(2, 'Meena', 'Tea', 50, '2025-09-10')
(3, 'Rajesh', 'Sandwich', 150, '2025-09-11')
This shows how powerful multiple tables are. With just one query, you can see the full
picture: who ordered what and when.
Why Multiple Tables Matter
No repetition → Rajesh’s details are written once in the Customer table.
Flexibility → Adding a new dish doesn’t mess up old data.
Accuracy → If Rajesh changes his phone, you update it in one place.
Easy relationships → You can easily see links between customers, orders, and menu
items.
So, programming with multiple tables is like organizing your café with separate ledgers for
customers, menu, and orders. Everything is clean, efficient, and easy to manage.
(b) Data Modelling
Now, let’s go one step further. Before you even create those tables in your café’s database,
you need a blueprint. Just like an architect draws a design before building a house, in
databases, we use data modelling to design the structure of data.
Easy2Siksha.com
What is Data Modelling?
Data modelling is the process of organizing data into logical structures so that it makes
sense and can be used effectively.
Think of it like designing the café before constructing it. You wouldn’t just randomly put
chairs and tables, right? You would plan the entrance, kitchen, and seating area. Similarly,
data modelling helps us plan where and how data will be stored.
Levels of Data Modelling
There are three main levels:
1. Conceptual Data Model (The Dream Stage)
o Big picture design.
o Just like drawing a rough sketch of your café on paper.
o Example: You note down “We need Customers, Menu, Orders, and
Payments.”
2. Logical Data Model (The Blueprint Stage)
o More detail: you decide the attributes (columns) of each table.
o Example: For Customer → Customer_ID, Name, Phone.
3. Physical Data Model (The Construction Stage)
o Final step where you decide how the database will actually be built in SQL.
o Example: Deciding data types (like INTEGER, TEXT).
Relationships in Data Modelling
The most beautiful part of data modelling is relationships.
One-to-One → One customer has one loyalty card.
One-to-Many → One customer can place many orders.
Many-to-Many → Many customers can order many items.
In our café story, the Order Table is the bridge that connects Customers with Menu items.
Example: Entity-Relationship (ER) Diagram
In data modelling, we often use diagrams to visualize data.
For our café:
Customer (Customer_ID, Name, Phone)
Easy2Siksha.com
Menu (Item_ID, Item_Name, Price)
Orders (Order_ID, Customer_ID, Item_ID, Date)
Relationships:
Customer → Orders (One-to-Many)
Menu → Orders (One-to-Many)
This ER diagram acts like the café’s floor plan.
Python Example (Data Modelling in Action)
In the previous Python code, we already converted a data model into actual tables. That was
the physical model stage.
If we wanted to expand, we could add a Payment Table.
cursor.execute("""CREATE TABLE IF NOT EXISTS Payment(
Payment_ID INTEGER PRIMARY KEY,
Order_ID INTEGER,
Amount INTEGER,
Method TEXT,
FOREIGN KEY(Order_ID) REFERENCES Orders(Order_ID)
)""")
Now, each order can be linked to a payment and you can track whether it was paid by
cash, card, or UPI.
Why Data Modelling Matters
Clarity → You know exactly how data is organized.
Efficiency → Queries run faster because the structure is optimized.
Scalability → As the café grows, you can add more tables without breaking the
system.
Accuracy → Reduces errors and confusion.
Without data modelling, databases become messy just like a café built without a floor
plan would collapse into chaos.
Conclusion
Let’s return to our café. By now, you:
Easy2Siksha.com
Learned how to organize information into multiple tables, so everything is neat,
efficient, and connected.
Understood the role of data modelling as the blueprint that guides the creation of
those tables.
Programming with multiple tables is like running your café with different ledgers for
customers, menu, and orders everything stays clean and easy. Data modelling is like the
café’s floor plan — it tells you where each piece of information belongs.
Both are essential. Without multiple tables, you drown in a sea of repeated information.
Without data modelling, you wouldn’t even know how to start.
In real life whether you’re running a café, building an e-commerce website, or managing
a hospital database these two concepts form the foundation of database management.
They make sure your data is reliable, accurate, and ready to serve you just like a steaming
cup of hot coffee at the right time.
“This paper has been carefully prepared for educational purposes. If you notice any mistakes or
have suggestions, feel free to share your feedback.”